<template>
  <div class="my-team-spaces-container">
    <a-card title="我的团队空间" :bordered="false">
      <!-- 顶部操作区域 -->
      <div class="header-actions">
        <a-space>
          <a-button @click="fetchTeamSpaceList">
            <template #icon><ReloadOutlined /></template>
            刷新
          </a-button>
        </a-space>
      </div>

      <!-- 团队空间卡片列表 -->
      <div class="space-cards">
        <a-spin :spinning="loading">
          <a-row :gutter="[24, 24]" v-if="teamSpaceList.length > 0">
            <a-col
              :xs="24"
              :sm="12"
              :md="8"
              :lg="6"
              v-for="teamSpace in teamSpaceList"
              :key="teamSpace.id"
            >
              <a-card class="space-card" hoverable @click="handleViewSpace(teamSpace)">
                <template #actions>
                  <TeamOutlined @click.stop="handleManageMembers(teamSpace)" title="成员管理" />
                  <EyeOutlined @click.stop="handleViewSpace(teamSpace)" title="查看图片" />
                </template>

                <div class="space-card-content">
                  <div class="space-icon">
                    <TeamOutlined style="color: #722ed1" />
                  </div>
                  <div class="space-info">
                    <h3 class="space-name">{{ teamSpace.spaceVO?.spaceName || '未命名空间' }}</h3>
                    <p class="space-description">
                      团队空间 · {{ getSpaceRoleText(teamSpace.spaceRole) }}
                    </p>
                  </div>
                </div>

                <div class="space-stats">
                  <a-tag :color="getSpaceRoleColor(teamSpace.spaceRole)">
                    {{ getSpaceRoleText(teamSpace.spaceRole) }}
                  </a-tag>
                  <div class="usage-info" v-if="teamSpace.spaceVO">
                    <div class="usage-item">
                      <span class="usage-label">存储:</span>
                      <span class="usage-value">
                        {{ formatFileSize(teamSpace.spaceVO.totalSize) }} /
                        {{ formatFileSize(teamSpace.spaceVO.maxSize) }}
                      </span>
                    </div>
                    <a-progress
                      :percent="
                        calculateUsageRate(teamSpace.spaceVO.totalSize, teamSpace.spaceVO.maxSize)
                      "
                      size="small"
                      :stroke-color="
                        getUsageColor(teamSpace.spaceVO.totalSize, teamSpace.spaceVO.maxSize)
                      "
                    />
                    <div class="usage-item">
                      <span class="usage-label">图片:</span>
                      <span class="usage-value">
                        {{ teamSpace.spaceVO.totalCount }} / {{ teamSpace.spaceVO.maxCount }}
                      </span>
                    </div>
                    <a-progress
                      :percent="
                        calculateUsageRate(teamSpace.spaceVO.totalCount, teamSpace.spaceVO.maxCount)
                      "
                      size="small"
                      :stroke-color="
                        getUsageColor(teamSpace.spaceVO.totalCount, teamSpace.spaceVO.maxCount)
                      "
                    />
                  </div>
                </div>

                <div class="join-time">加入时间: {{ formatDateTime(teamSpace.createTime) }}</div>
              </a-card>
            </a-col>
          </a-row>

          <!-- 空状态 -->
          <a-empty v-else description="暂未加入任何团队空间" />
        </a-spin>
      </div>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { ReloadOutlined, TeamOutlined, EyeOutlined } from '@ant-design/icons-vue'
import { listMyTeamSpaces } from '@/api/space-user'
import type { SpaceUserVO } from '@/types/space-user'
import { getSpaceRoleText, getSpaceRoleColor } from '@/types/space-user'
import { formatFileSize, calculateUsageRate } from '@/types/space'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const teamSpaceList = ref<SpaceUserVO[]>([])

// 获取团队空间列表
const fetchTeamSpaceList = async () => {
  try {
    loading.value = true
    const response = await listMyTeamSpaces()

    // 处理不同的响应结构
    if (response.data.data) {
      teamSpaceList.value = response.data.data
    } else if (Array.isArray(response.data)) {
      // 如果 response.data 本身就是数组
      teamSpaceList.value = response.data
    } else {
      teamSpaceList.value = []
    }
  } catch (error: unknown) {
    console.error('获取团队空间列表失败:', error)
    message.error('获取团队空间列表失败')
  } finally {
    loading.value = false
  }
}

// 获取使用率颜色
const getUsageColor = (used: number | string, total: number | string) => {
  const rate = calculateUsageRate(used, total)
  if (rate >= 90) return '#ff4d4f'
  if (rate >= 70) return '#fa8c16'
  return '#52c41a'
}

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
  })
}

// 查看空间
const handleViewSpace = (teamSpace: SpaceUserVO) => {
  if (!teamSpace.spaceVO) return
  // 使用字符串类型的spaceId，避免精度丢失
  router.push({
    name: 'SpacePictures',
    params: { spaceId: String(teamSpace.spaceId) },
    query: { spaceName: teamSpace.spaceVO.spaceName },
  })
}

// 管理团队成员
const handleManageMembers = (teamSpace: SpaceUserVO) => {
  // 只有管理员才能管理成员
  if (teamSpace.spaceRole !== 'admin') {
    message.warning('只有管理员才能管理团队成员')
    return
  }
  if (!teamSpace.spaceVO) return
  // 使用字符串类型的spaceId，避免精度丢失
  router.push({
    name: 'SpaceTeamMember',
    params: { spaceId: String(teamSpace.spaceId) },
    query: { spaceName: teamSpace.spaceVO.spaceName },
  })
}

// 组件挂载时获取数据
onMounted(() => {
  fetchTeamSpaceList()
})
</script>

<style scoped>
.my-team-spaces-container {
  padding: 24px;
}

.header-actions {
  margin-bottom: 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.space-cards {
  min-height: 400px;
}

.space-card {
  height: 100%;
  transition: all 0.3s;
}

.space-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.space-card-content {
  display: flex;
  align-items: flex-start;
  margin-bottom: 16px;
}

.space-icon {
  font-size: 24px;
  margin-right: 12px;
  color: #1890ff;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  background: #f0f2f5;
  border-radius: 8px;
}

.space-info {
  flex: 1;
}

.space-name {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 600;
  color: #262626;
}

.space-description {
  margin: 0;
  font-size: 12px;
  color: #8c8c8c;
}

.space-stats {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 12px;
}

.usage-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.usage-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
}

.usage-label {
  color: #666;
}

.usage-value {
  color: #262626;
  font-weight: 500;
}

.join-time {
  font-size: 12px;
  color: #8c8c8c;
  text-align: center;
  padding-top: 8px;
  border-top: 1px solid #f0f0f0;
}

:deep(.ant-card-body) {
  padding: 20px;
}

:deep(.ant-card-actions) {
  background: #fafafa;
}

:deep(.ant-progress-line) {
  margin: 2px 0;
}

:deep(.ant-empty-description) {
  color: #999;
}
</style>
